import {AfterViewInit, Component, OnInit, ViewChild} from "@angular/core";
import {Util} from "../../../common/util";
import {ActivatedRoute} from "@angular/router";
import {BankAccountManageService} from "./bank-accountManage.service";
import {PaginationModel} from "../../../widgets/pagination/pagination.component";

import * as _ from 'lodash';

@Component({
  templateUrl: './bank-accountManage.component.html',
  styleUrls: ['./bank-accountManage.component.scss']
})

export class BankAccountManageComponent implements OnInit, AfterViewInit {

  public $ = window["$"];

  // 列表当前页全选标记
  public isCheckedAll = false;

  // 当前模态框类型 update/更新，add/新增
  public type = "add";

  // 查询条件数据
  public searchBody: any = {
    c_fund_code: '',     // 基金代码
    vc_fund_name: '',    // 基金名称
    c_pay_type: ''   // 款项类型
  };

  // 请求返回的数据列表
  public accountList: any;

  // 模态框内数据对象
  public commonModalData: any = {};

  // 模态框内下拉列表数据
  public commonModalSelectData:any ;

  // 模态框更新变量对象,用与修改更新或新建参数配置
  public commonModalUpdateData: any = {
    c_fund_code: "",
    vc_fund_name: "",
    c_payaccount_bank: "",
    c_payaccount: "",
    c_acc_bankname: "",
    c_acc_name: "",
    c_acc_no: "",
    c_pay_type: "",
    c_acc_addr: "",
    c_usage: "",
    c_id:"",
    c_sys_code:"",
    c_payaccount_name: "",
    c_payaccount_sys: ""
  };


  // 二级模态框（基金选择列表）的查询条件对象
  public modalFundSearch: any = {
    c_pay_type: "",    // 属性由一级模态框传递
    c_fund_code: "",
    vc_fund_name: ""
  };

  // 二级模态框（基金选择列表）请求返回的基金数据对象
  public modalFundData: any;

  // 二级模态框（基金选择列表）内选中数据对象
  public checkedData = {
    c_fund_code: '',
    vc_fund_name: '',
    c_payaccount_bank:'',
    c_payaccount:'',
    c_payaccount_name:''
  };

  // 分页数据模型
  public pageInfo: PaginationModel = {
    currentPageNum: 1,
    pageSize: 10,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };

  constructor(public service: BankAccountManageService) {

  }

  ngOnInit() {
    // 页面首次加载
    this.search();
    this.getModalSelect();
  }

  ngAfterViewInit(): void {
    //  调用时间插件
    Util.daterangepickerPluginInit(".daterangepicker-plugin");
    Util.datepickerPluginInit(".daterangepicker-single");
  }

  /**
   * [checkedAll 列表当前页全选]
   */
  checkedAll() {
    if (this.isCheckedAll) { // 更新为全选
      _.forEach(this.accountList, item => {
        item.isChecked = true;
      });
    } else { // 更新为不全选
      _.forEach(this.accountList, item => {
        item.isChecked = false;
      });
    }
  }

  /**
   * [checked 是否需要更新全选]
   * @param {[type]} item [实例对象]
   */
  checked(item) {
    if (item.isChecked) {
      const temp = _.find(this.accountList, {isChecked: false});
      if (!temp) { // 全选重置为 true
        this.isCheckedAll = true;
      }
    } else { // 全选重置为 false
      this.isCheckedAll = false;
    }
  }

  // 获取模态框下拉列表
  public getModalSelect(){
    return this.service.getModalSelectData().subscribe(result =>{
      if(result){
        this.commonModalSelectData = result;
      }
    })
  }

  public search() {
    return this.getListData(this.wrapperSearchModule());
  }

  public resetSearch() {
    this.searchBody = {
      c_fund_code: '',     // 基金代码
      vc_fund_name: '',    // 基金名称
      c_pay_type: ''   // 款项类型
    };
  }

  /**
   * 请求列表数据函数
   * @param {any} param 查询参数
   * @param {number} [currentPageNum=this.pageInfo.currentPageNum]
   * @param {number} [pageSize=this.pageInfo.pageSize]
   * @returns
   * @memberof TransferInstructionOptionComponent
   */
  public getListData(param, currentPageNum: number = this.pageInfo.currentPageNum,
                     pageSize: number = this.pageInfo.pageSize) {
    return this.service.getListData(param, currentPageNum, pageSize).subscribe(result => {
      if (result != null && result.data != null && result.data.list != null) {
        this.accountList = [];
        this.accountList = result.data.list;
        this.pageInfo.totalPages = result.data.pages;
        this.pageInfo.total = result.data.total;
        this.pageInfo.startRow = result.data.startRow;
        this.pageInfo.endRow = result.data.endRow;
      }
    });
  }

  public wrapperSearchModule() {
    const param = this.$.extend(true, {}, this.searchBody);
    return param;
  }

  /**
   * 删除确认
   * @param item 如果是行内删除
   */
  public deleteAccountConfig(item?){
    const that = this;
    if(item){
      const data = {
        c_id:item.c_id
      }
      return window["swal"]({
        title: "提示",
        text: "确定要删除吗？",
        type: "info",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        closeOnConfirm: false,
        closeOnCancel: true,
        showLoaderOnConfirm: true
      },
      function (isConfirm) {
        if (isConfirm) {
          return that.service.deleteAccount(data).subscribe(result => {
            if(result){
              window["swal"]("删除成功", "", "success");
              that.search();
            }
          });
        }
      });
    }
    const data = _.filter(this.accountList,{isChecked:true});
    if(data.length === 0){
      return window["swal"]("提示", "请选择一行进行操作", "warning");
    }
    window["swal"]({
      title: "提示",
      text: "确定要删除吗？",
      type: "info",
      showCancelButton: true,
      confirmButtonColor: "#DD6B55",
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      closeOnConfirm: false,
      closeOnCancel: true,
      showLoaderOnConfirm: true
    },
    function (isConfirm) {
      if (isConfirm) {
        return that.service.deleteAccount(that.takeIdToDelete(data)).subscribe(result => {
          if(result){
            window["swal"]("删除成功", "", "success");
            that.search();
          }
        });
      }
    });
  }

  // 取出id进行删除动作
  takeIdToDelete(data){
    const idObject = {
      c_id:[]
    };
    data.forEach(function(item){
      idObject.c_id.push(item.c_id);
    });
    return idObject;
  }

  // 打开修改或新增账号模态框
  public openCommonModal(type, item?) {
    this.type = type;
    if (type === "update") {
      this.commonModalData = this.$.extend(true, {}, item);
    }
    if (type === "add") {
      this.commonModalData = {};
    }
    this.$("#commonModal").modal('show');
  }


  // 新增或更新账号配置
  addOrUpateAccountConfig() {
    const that = this;
    if (this.type === "update") {
      window["swal"]({
          title: "提示",
          text: "是否要更新基金配置？",
          type: "info",
          showCancelButton: true,
          confirmButtonColor: "#DD6B55",
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          closeOnConfirm: false,
          closeOnCancel: true,
          showLoaderOnConfirm: true
        },
        function (isConfirm) {
          if (isConfirm) { // 确认
            const param = that.copyData(that.commonModalData, that.commonModalUpdateData);
            that.service.addORUpdateAccountConfig(param, that.type).subscribe(data => {
              if (data) {
                window["swal"]("更新成功", "", "success");
                that.search();
              }
            });
          } else { // 取消
            // window["swal"]("Cancelled", "Your imaginary file is safe :)", "error");
          }
        });
    } else {
      window["swal"]({
          title: "",
          text: "是否确定要新增基金配置信息?",
          type: "info",
          showCancelButton: true,
          confirmButtonColor: "#DD6B55",
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          closeOnConfirm: false,
          closeOnCancel: true,
          showLoaderOnConfirm: true
        },
        function (isConfirm) {
          if (isConfirm) { // 确认
            const param = that.copyData(that.commonModalData, that.commonModalUpdateData);
            that.service.addORUpdateAccountConfig(param, that.type).subscribe(data => {
              if (data) {
                window["swal"]("新增成功", "", "success");
                that.search();
              }
            });
          } else { // 取消
            // window["swal"]("Cancelled", "Your imaginary file is safe :)", "error");
          }
        });

    }
  }

  // 拷贝相同属性
  // @param p 目标变量
  // @param c 变量模板
  public copyData(p, c) {
    for (let i in p) {
      for (let a in c)
        if (i === a) {
          c[a] = p[i];
        }
    }
    return c;
  }


  // 打开二级模态框（基金选择）并查询
  public openChooseFundModal(item) {
    if(item.c_pay_type){
      this.modalFundSearch.c_pay_type = item.c_pay_type;
      this.searchFundList(item);
      this.$("#chooseFundModal").modal('show');
    }else{
      window["swal"]("提示", "请选择业务类型再进行选择基金操作", "info");
    }
  }


  // 二级模态框（基金选择）切换选中状态
  fundModalChecked(item, $event) {
    if ($event.target.checked) {
      this.checkedData = {
        // c_fund_code是querycondition接口返回的基金代码字段名，vc_fund_code是trustAccount返回的基金代码字段名
        // 这里应该是后端人员搞错了
        c_fund_code: item.vc_fund_code,
        vc_fund_name: item.vc_fund_name,
        c_payaccount_bank:item.vc_account_bank,
        c_payaccount:item.vc_account,
        c_payaccount_name:item.vc_account_name
      };
    }
  }

  // 二级模态框查询函数
  public searchFundList(item?) {
    const param = {
      c_pay_type: this.modalFundSearch.c_pay_type,
      vcFundCode: this.modalFundSearch.c_fund_code ? this.modalFundSearch.c_fund_code : '',
      vcFundName: this.modalFundSearch.vc_fund_name ? this.modalFundSearch.vc_fund_name : '',
      pageSize: 10000,
      page: 1
    };
    this.service.searchFundList(param).subscribe(result => {
      if (result != null) {
        this.modalFundData = result;
      }
    });
  }

  // 二级模态框确定按钮，将选择的基金返回到上一级模态框中
  public confirmFund() {
    this.commonModalData.c_fund_code = this.checkedData.c_fund_code;
    this.commonModalData.vc_fund_name = this.checkedData.vc_fund_name;
    this.commonModalData.c_payaccount_bank = this.checkedData.c_payaccount_bank; // 付款银行名称
    this.commonModalData.c_payaccount = this.checkedData.c_payaccount
    this.commonModalData.c_payaccount_name = this.checkedData.c_payaccount_name
    this.$("#chooseFundModal").modal('hide');
  }

  // 二级模态框关闭，并清空数据
  public closeFundModal() {
    this.modalFundSearch = {
      c_pay_type: "",
      c_fund_code: "",
      vc_fund_name: ""
    };
    this.$("#chooseFundModal").modal('hide');
  }

  /**
   * 根据页码请求查询相关配置列表数据,如果当前活动页码就是目标页码，则不进行任何查询
   * 直接返回
   * @param {currentPageNum}
   */
  public pageNavigation(currentPageNum: number) {
    this.pageInfo.currentPageNum = currentPageNum;
    this.search();
  }

  /**
   * 改变每页显示记录数
   * @param {pageSize}
   */
  public pageSizeChange(pageSize: number) {
    if (pageSize !== this.pageInfo.pageSize) {
      this.pageInfo.pageSize = pageSize;
      this.pageInfo.currentPageNum = 1;
      this.search();
    }
  }

}
